Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add collapseWithKeys to Collection #52347

Merged
merged 1 commit into from
Aug 1, 2024

Conversation

jasonmccreary
Copy link
Contributor

I had the need to collapse a collection of nested arrays while preserving their keys. Neither the flatten nor collapse methods have a flag for preserving keys. While it may not for flatten, the option may make sense for collapse given its single depth.

Consider the following collection (before/after):

[[1 => 'a'], [3 => 'c'], [2 => 'b']] // before
[1 => 'a', 3 => 'c', 2 => 'b']       // after

Of course, you may achieve the after result using mapWithKeys and a custom callback or some pipeline of collection methods. But this seems like a common enough use case for a collapseWithKeys (or better name) to exist.

@jasonmccreary
Copy link
Contributor Author

Note, I didn't add this method to Arr or Eloquent\Collection. I don't see a use case for Eloquent\Collection, and didn't know the level of method symmetry between the Arr and Collection classes.

@taylorotwell taylorotwell merged commit c917b0e into laravel:11.x Aug 1, 2024
31 checks passed
@jasonmccreary jasonmccreary deleted the collapse-with-keys branch August 1, 2024 16:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants